package accounts

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"minititok/Entities"
	"minititok/Services"
	"net/http"
)

func register(c *gin.Context) {
	var body struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
		Phone    string `json:"phone" binding:"required"`
		Email    string `json:"email" binding:"required"`
		Nickname string `json:"nickname" binding:"required"`
	}

	if err := c.ShouldBindJSON(&body); err != nil {
		_ = c.Error(fmt.Errorf("请求格式错误:" + err.Error()))
		c.JSON(http.StatusBadRequest, gin.H{"customMessage": "请求格式错误"})
		return
	}
	user := &Entities.User{
		Username: body.Username,
		Password: body.Password,
		Phone:    body.Phone,
		Email:    body.Email,
		Nickname: body.Nickname,
	}
	if err := Services.RegisterUser(user); err != nil {
		_ = c.Error(fmt.Errorf("数据库错误,用户储存失败:" + err.Error()))
		c.JSON(http.StatusBadRequest, gin.H{"customMessage": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "msg": "success"})
}
